//
//  Common.m
//  Medicare
//
//  Created by admin on 16/5/6.
//  Copyright © 2016年 iflytek. All rights reserved.
//

#import "Common.h"
#import "UIImage+ImageEffects.h"
#import "MyTextField.h"
#import "NSMutableArray+FilterElement.h"
#import<CommonCrypto/CommonDigest.h>
#import "IFMySchedulingPublicDefines.h"

@implementation Common

+ (UIColor *)hexToColor:(NSString *)str
{
    if (!str || [str isEqualToString:@""]) {
        return nil;
    }
    unsigned red,green,blue;
    NSRange range;
    range.length = 2;
    range.location = 1;
    [[NSScanner scannerWithString:[str substringWithRange:range]] scanHexInt:&red];
    range.location = 3;
    [[NSScanner scannerWithString:[str substringWithRange:range]] scanHexInt:&green];
    range.location = 5;
    [[NSScanner scannerWithString:[str substringWithRange:range]] scanHexInt:&blue];
    UIColor *color= [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:1];
    
    return color;
}

+ (AppDelegate *)getDelegate {
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}

+ (NSString *)cachPath {
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}

+ (id)jsonToObject:(NSString *)jsonStr {
    
    if (jsonStr && ![jsonStr isEqualToString:@""]) {
        return [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
    } else {
        return nil;
    }
}

+ (NSString *)objectToJson:(id)obj {
    
    if (obj) {
        return @"";
    } else {
        return [[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
    }
}

//+ (void)processPrivateCloudIPWithString:(NSString *)string
//{
//
//    if (string.length) {
//        NSArray *stringParts = [string componentsSeparatedByString:@","];
//        NSString *firstString = [stringParts.firstObject stringByReplacingOccurrencesOfString:@"http://" withString:@""];
//        [IFlyUserDefault setObject:firstString forKey:PRIVATE_MSC_URL];
//        [IFlyUserDefault setObject:[NSString stringWithFormat:@"%@?usr_id=medical_iflytek&text=%%@&ver=2.0&method=query&appid=56fb3271",stringParts.lastObject] forKey:PRIVATE_MSC_URL_NLP];
//    }
//    else
//    {
//        [IFlyUserDefault setObject:@"" forKey:PRIVATE_MSC_URL];
//        [IFlyUserDefault setObject:@"" forKey:PRIVATE_MSC_URL_NLP];
//    }
//#if 0
//#if DEBUG
//    [IFlyUserDefault setObject:@"" forKey:PRIVATE_MSC_URL];
//    [IFlyUserDefault setObject:@"" forKey:PRIVATE_MSC_URL_NLP];
//#endif
//#endif
//}

+ (UIImage *)blurredImageWithImage:(UIImage *)image
{
    return [image applyBlurWithRadius:20 tintColor:[UIColor colorWithWhite:0.21 alpha:0.73] saturationDeltaFactor:1.3 maskImage:nil];
}

+ (UIImage *)snapshot:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size,YES,0);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

+ (BOOL)addGuideWithImage:(UIImage *)image
                       vc:(UIViewController *)vc
       guideDefaultString:(NSString *)defaultString
                 selector:(SEL)selector
{
    if (![IFlyUserDefault objectForKey:defaultString]) {
        UIView *backgroundView = [[UIView alloc] initWithFrame:vc.view.window.bounds];
        backgroundView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        UIImageView *guide = [[UIImageView alloc] initWithFrame:backgroundView.bounds];
        [backgroundView addSubview:guide];
        guide.image = image;
        [backgroundView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:vc action:selector]];
        [[UIApplication sharedApplication].keyWindow addSubview:backgroundView];
        [IFlyUserDefault setObject:@YES forKey:defaultString];
        return YES;
    }
    else
    {
        return NO;
    }
}

//runtime获取属性
+ (BOOL) isPropertyAvailableWithClass:(Class) myClass varName:(NSString *)name
{
    unsigned int outCount, i;
    Ivar *ivars = class_copyIvarList(myClass, &outCount);
    for (i = 0; i < outCount; i++) {
        Ivar property = ivars[i];
        NSString *keyName = [NSString stringWithCString:ivar_getName(property) encoding:NSUTF8StringEncoding];
        keyName = [keyName stringByReplacingOccurrencesOfString:@"_" withString:@""];
        if ([keyName isEqualToString:name]) {
            //释放varList
            if (ivars) {
                free(ivars);
            }
            return YES;
        }
    }
    if (ivars) {
      free(ivars);
    }
    return NO;
}

+ (UIViewController *)getPresentedViewController {
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIViewController *appRootVC = appDelegate.window.rootViewController;
    UIViewController *topVC = appRootVC;
    if (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    return [self getViewControllerWith:topVC];
}

+ (UIViewController *)getViewControllerWith:(UIViewController *)viewController {
    
    if (viewController.presentedViewController) {
        return  [self getViewControllerWith:viewController.presentedViewController];
    } else {
        return viewController;
    }
    
}

+ (void)setTextFieldClearButtonWithSuperView:(UIView *)superView
{
    for (UITextField *textField in superView.subviews) {
        if ([textField isMemberOfClass:[UITextField class]] || [textField isMemberOfClass:[MyTextField class]] ||
            [textField isMemberOfClass:[IFLYTextField class]]) {
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            UIButton *clearButton = [textField valueForKey:@"_clearButton"];
            [clearButton setImage:[UIImage imageNamed:@"login_name_delete_icon_2_0"] forState:UIControlStateNormal];
            [clearButton setImage:[UIImage imageNamed:@"login_name_delete_icon_2_0"] forState:UIControlStateHighlighted];
        }
    }
}

+ (void)exchangeString:(NSString *)newString withTextView:(UITextView *)textView isBackward:(BOOL)isBackward
{
    NSMutableString *oldString = [NSMutableString stringWithString:textView.text];
    NSRange rg = textView.selectedRange;
    if (rg.location == NSNotFound) {
        
        // 如果没找到光标,就把光标定位到文字结尾
        rg.location = textView.text.length;
    }
    if (isBackward) {
        if (rg.length == 0) {
            rg.length = 1;
        }
        if (rg.location > 0) {
            rg.location--;
        }
        if (rg.length < 2) {
            if (0 == rg.location) {
                if (oldString.length > 0) {
                    if ([[oldString substringToIndex:1] isEqualToString:@"\n"]) {
                        rg.length = 1;
                    }
                }
                else
                {
                    rg.length = 0;
                }
            }
            else
            {
                rg.length = 1;
            }
        }
    }
    
    // 1.3 替换选中文字
    
    [oldString replaceCharactersInRange:rg withString:newString];
    textView.text = oldString;
    
    // 1.4 定位光标
    textView.selectedRange = NSMakeRange(rg.location + newString.length, 0);
}
#pragma mark - 私有
- (void)guideClicked:(UITapGestureRecognizer *)sender
{
    [sender.view removeFromSuperview];
}


//获取拼音首字母(传入汉字字符串, 返回大写拼音首字母)
+ (NSString *)firstCharactor:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pinYin = [str capitalizedString];
    //获取并返回首字母
    return [pinYin substringToIndex:1];
}


+(UIImage *) imageWithColor:(UIColor*)color andHeight:(CGFloat)height
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

+ (NSArray *)searchWithFieldArray:(NSArray *)fieldArray
                      inputString:(NSString *)inputString
                          inArray:(NSArray *)array
{
    if (![array count] || ![fieldArray count])
    {
        return nil;
    }
    
    NSPredicate *scopePredicate;
    NSMutableArray *backArray = [NSMutableArray array];
    
    for (NSString *fieldString in fieldArray)
    {
        NSArray *tempArray = [NSArray array];
        scopePredicate = [NSPredicate predicateWithFormat:@"SELF.%@ contains[c] %@", fieldString, inputString];
        tempArray = [array filteredArrayUsingPredicate:scopePredicate];
        for (NSObject *object in tempArray)
        {
            if (![backArray containsObject:object])
            {
                [backArray nd_addObj:object];
            }
        }
    }
    
    return backArray;
}

+ (NSArray *)searchWithAllFieldArray:(NSArray *)allFieldArray
                         inputString:(NSString *)inputString
                          inAllArray:(NSArray *)allArray
{
    NSInteger count = allArray.count;
    
    if (allFieldArray.count != allArray.count || 0 == count)
    {
        return nil;
    }
    
    NSMutableArray *backArray  = [NSMutableArray array];
    
    for (NSInteger i = 0; i < count; i++)
    {
        NSArray *tempArray = [self searchWithFieldArray:allFieldArray[i] inputString:inputString inArray:allArray[i]];
        [backArray nd_addObj:tempArray];
    }
    
    return backArray;
}
#pragma mark 数组排序
+ (NSMutableArray *)sortFirstStrWithArray:(NSArray *)array {
    
    NSMutableArray *resultMua = [NSMutableArray arrayWithArray:array];
    NSSortDescriptor *desc = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES]; // 升序
    [resultMua sortUsingDescriptors:[NSArray arrayWithObject:desc]];
    
    NSMutableArray *removeArray = [NSMutableArray array];
    for (NSString *first in resultMua) {
        if ([first isEqualToString:@"#"]) {
            [removeArray addObject:first];
            break;
        }
        
    }
    // 想过滤# 就先移除
    [resultMua removeObjectsInArray:removeArray];
    
    // 然后根据遍历的一个一个添加
    [resultMua addObjectsFromArray:removeArray];
    
    
    return resultMua;
    
}
//用来判断一个字符串是否全是空格
+ (BOOL) isEmpty:(NSString *) str {
    if (!str) {
        return true;
    } else {
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        if ([trimedString length] == 0) {
            return true;
        } else {
            return false;
        }
    }
}



//圆角矩形
+(UIImage *)drawRectangle:(CGRect)rect withRadius:(float)radius AndwithLineWidth:(CGFloat )lineWidth AndwithLineColor:(UIColor *)lineColor AndwithFillColor:(UIColor *)fillColor {
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
    CGContextRef     context = UIGraphicsGetCurrentContext();
    CGFloat borderDiameter  =  rect.size.width  - radius;
    CGRect borderRect   =   (CGRect){radius/2, radius/2, CGSizeMake(borderDiameter, borderDiameter)};
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:borderRect cornerRadius:radius];
    CGContextSetLineWidth(context, lineWidth);
    // CGContextAddPath(context,bezierPath.CGPath);
    //  bezierPath.lineWidth = 20;
    [fillColor setFill];
    [lineColor setStroke];
    [bezierPath stroke];
    CGContextAddPath(context, bezierPath.CGPath);
    CGContextDrawPath(context,kCGPathFillStroke);
    CGContextStrokePath(context);
    CGContextClip(UIGraphicsGetCurrentContext());
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

//保存图片
+(void)saveImageDocuments:(UIImage *)image AndImageName:(NSString *)name {
    [[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation(image) forKey:name];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

// 读取并存贮到相册
+(UIImage *)getDocumentImageAndImageName:(NSString *)pictureName {
    NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:pictureName];
    UIImage* image = [UIImage imageWithData:imageData];
    return image;
}


//MD5加密
+ (NSString *)md5:(NSString *)input {
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr,(CC_LONG)strlen(cStr),digest); // This is the md5 call
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return  output;
}

/**
 * 传入参数与url，拼接为一个带参数的url
 **/
+(NSString *) connectUrl:(NSDictionary *)params url:(NSString *) urlLink {
    // 初始化参数变量
    NSString *str = @"&";
    // 快速遍历参数数组
    for(id key in params) {
        NSLog(@"key :%@  value :%@", key, [params objectForKey:key]);
        str = [str stringByAppendingString:key];
        str = [str stringByAppendingString:@"="];
        str = [str stringByAppendingString:[params objectForKey:key]];
        str = [str stringByAppendingString:@"&"];
    }
    // 处理多余的&以及返回含参url
    if (str.length > 1) {
        // 去掉末尾的&
        str = [str substringToIndex:str.length - 1];
        if (str.length > 1) 
        str = [str substringFromIndex:1];
        // 返回含参url
        return [urlLink stringByAppendingString:str];
    }
    return Nil;
}
//获取当前时间
+ (NSString *)getCurrentDateWithTheDateFormat:(NSString *)dateFormatString {
    NSDate *senddate = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:dateFormatString];
    return [dateformatter stringFromDate:senddate];
}
//获取两个日期之间相差的天数
+ (NSInteger)numberOfDaysWithFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate { 
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents    * comp = [calendar components:NSCalendarUnitDay
                                             fromDate:fromDate
                                               toDate:toDate
                                              options:NSCalendarWrapComponents];
    return comp.day;
}

/**
 *  判断一个字符串是否为空
 */
+(BOOL) isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    if ([string isEqualToString:@"(null)"]) {
        return YES;
    }
    
    return NO;
}



@end
